<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showSuccessToast, showFailToast, showLoadingToast, closeToast } from 'vant'

interface HealthDetail {
  columnId: number
  columnName: string
  consultationMing: string
  introduction: string
  doctorId?: number
  spleen?: string
  anticancer?: string
  beneficial?: string
  function?: string
}

interface ApiResponse {
  mes: string
  code: number
  data: HealthDetail[]
}

interface DoctorInfo {
  doctorId: number
  doctorName: string
  position: string
  department: string
  address: string
  follow: boolean
}

interface DoctorApiResponse {
  mes: string
  code: number
  data: DoctorInfo[]
}

const router = useRouter()
const route = useRoute()

// 文章数据
const articleData = ref<HealthDetail>({
  columnId: 0,
  columnName: '',
  consultationMing: '',
  introduction: '',
  doctorId: 0,
  spleen: '',
  anticancer: '',
  beneficial: '',
  function: ''
})

// 是否已收藏
const isCollected = ref(false)

// 是否已点赞
const isLiked = ref(false)

// 加载状态
const loading = ref(false)

// 医生信息
const doctorInfo = ref<DoctorInfo>({
  doctorId: 0,
  doctorName: '',
  position: '',
  department: '',
  address: '',
  follow: false
})

// 获取文章详情
const fetchArticleDetail = async () => {
  try {
    loading.value = true
    showLoadingToast({
      message: '加载中...',
      forbidClick: true
    })
    
    const columnId = route.params.id as string
    
    if (!columnId) {
      showFailToast('文章ID不存在')
      router.back()
      return
    }
    
    const response = await fetch(`http://localhost:5104/api/Healthing/FanHealth?ColumnId=${columnId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'accept': 'text/plain'
      }
    })
    
    if (!response.ok) {
      throw new Error('网络请求失败')
    }
    
    const result: ApiResponse = await response.json()
    
    if (result.code === 300 && result.data && result.data.length > 0 && result.data[0]) {
      // 使用API返回的第一条数据
      articleData.value = result.data[0]
    } else {
      showFailToast(result.mes || '获取文章详情失败')
      // 如果API失败，尝试使用路由参数作为备选
      loadFromQueryParams()
    }
  } catch (error) {
    console.error('获取文章详情失败:', error)
    showFailToast('网络请求失败，请检查网络连接')
    
    // 如果API失败，使用路由参数作为备选
    loadFromQueryParams()
  } finally {
    loading.value = false
    closeToast()
  }
}

// 从路由查询参数加载数据
const loadFromQueryParams = () => {
  const columnId = route.params.id as string
  const columnName = route.query.columnName as string || ''
  const consultationMing = route.query.consultationMing as string || ''
  const introduction = route.query.introduction as string || ''
  const doctorIdParam = route.query.doctorId as string
  const spleen = route.query.spleen as string || ''
  const anticancer = route.query.anticancer as string || ''
  const beneficial = route.query.beneficial as string || ''
  const functionField = route.query.function as string || ''
  
      if (consultationMing) {
        articleData.value = {
          columnId: parseInt(columnId) || 0,
          columnName: columnName,
          consultationMing: consultationMing,
          introduction: introduction,
          doctorId: doctorIdParam ? parseInt(doctorIdParam) : undefined,
          spleen: spleen,
          anticancer: anticancer,
          beneficial: beneficial,
          function: functionField
        }
      }
}

// 获取医生信息
const fetchDoctorInfo = async (doctorId?: number) => {
  // 如果没有传入 doctorId，使用默认值 1
  const targetDoctorId = doctorId || 1
  
  try {
    const response = await fetch(`http://localhost:5029/api/Health/ShowDoctor?DoctorId=${targetDoctorId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'accept': 'text/plain'
      }
    })
    
    if (!response.ok) {
      throw new Error('网络请求失败')
    }
    
    const result: DoctorApiResponse = await response.json()
    
    if (result.code === 300 && result.data && result.data.length > 0 && result.data[0]) {
      doctorInfo.value = result.data[0]
    } else {
      console.warn('获取医生信息失败，使用默认数据')
    }
  } catch (error) {
    console.error('获取医生信息失败:', error)
    // 如果获取失败，保持默认值或使用空数据
  }
}

// 初始化数据
onMounted(async () => {
  await fetchArticleDetail()
  
  // 优先使用文章数据中的 doctorId，其次使用路由参数中的 doctorId，最后默认使用 1
  const doctorId = articleData.value.doctorId 
    || (route.query.doctorId as string ? parseInt(route.query.doctorId as string) : undefined)
    || 1
  
  await fetchDoctorInfo(doctorId)
})

// 关注作者
const handleFollow = async () => {
  doctorInfo.value.follow = !doctorInfo.value.follow
  if (doctorInfo.value.follow) {
    showSuccessToast('已关注')
  } else {
    showToast('已取消关注')
  }
  // 这里可以添加调用后端API更新关注状态的逻辑
}

// 收藏文章
const handleCollect = () => {
  isCollected.value = !isCollected.value
  if (isCollected.value) {
    showSuccessToast('已收藏')
  } else {
    showToast('已取消收藏')
  }
}

// 点赞数
const likesCount = ref(520)

// 点赞文章
const handleLike = () => {
  isLiked.value = !isLiked.value
  if (isLiked.value) {
    likesCount.value += 1
    showSuccessToast('点赞成功')
  } else {
    likesCount.value -= 1
    showToast('已取消点赞')
  }
}

// 评论（暂不可用）
const handleComment = () => {
  showToast('暂无法评论')
}
</script>

<template>
  <div class="article-detail-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="资讯详情"
      left-arrow
      fixed
      placeholder
      @click-left="router.back()"
    >
      <template #right>
        <van-icon name="ellipsis" size="20" />
        <van-icon name="eye-o" size="20" style="margin-left: 12px;" />
      </template>
    </van-nav-bar>

    <!-- 文章内容区域 -->
    <div class="article-content-wrapper">
      <!-- 文章标题和阅读量 -->
      <div class="article-header">
        <h1 class="article-title">{{ articleData.consultationMing }}</h1>
        <div class="view-count">
          <van-icon name="eye-o" size="14" />
          <span>2000人已读</span>
        </div>
      </div>

      <!-- 作者信息 -->
      <div class="author-info">
        <div class="author-avatar">👨‍⚕️</div>
        <div class="author-details">
          <div class="author-name">{{ doctorInfo.doctorName || '加载中...' }}</div>
          <div class="author-title">{{ doctorInfo.position }}</div>
          <div class="author-hospital">{{ doctorInfo.department }} {{ doctorInfo.address }}</div>
        </div>
        <van-button 
          :type="doctorInfo.follow ? 'default' : 'primary'"
          size="small" 
          class="follow-btn"
          @click="handleFollow"
        >
          {{ doctorInfo.follow ? '已关注' : '关注' }}
        </van-button>
      </div>

      <!-- 文章正文 -->
      <div class="article-body">
        <!-- 介绍段落 -->
        <div v-if="articleData.introduction" class="article-intro">
          {{ articleData.introduction }}
        </div>
        
        <!-- 分段内容 -->
        <div v-if="articleData.spleen" class="article-section">
          <div class="section-title">1、补脾益气</div>
          <div class="section-content">{{ articleData.spleen }}</div>
        </div>
        
        <div v-if="articleData.anticancer" class="article-section">
          <div class="section-title">2、抗癌</div>
          <div class="section-content">{{ articleData.anticancer }}</div>
        </div>
        
        <div v-if="articleData.beneficial" class="article-section">
          <div class="section-title">3、减肥</div>
          <div class="section-content">{{ articleData.beneficial }}</div>
        </div>
        
        <div v-if="articleData.function" class="article-section">
          <div class="section-title">4、缓解皮肤病</div>
          <div class="section-content">{{ articleData.function }}</div>
        </div>
        
        <div v-if="!articleData.introduction && !articleData.spleen && !articleData.anticancer && !articleData.beneficial && !articleData.function && loading" class="loading-text">
          加载中...
        </div>
      </div>

      <!-- 标签和发布时间 -->
      <div class="article-footer">
        <div class="article-tag">#{{ articleData.columnName }}</div>
        <div class="publish-time">发布于2020-01-01 15:20:20</div>
      </div>
    </div>

    <!-- 底部交互栏 -->
    <div class="bottom-bar">
      <div class="comment-input" @click="handleComment">
        <van-icon name="chat-o" size="18" />
        <span>暂无法评论</span>
      </div>
      <div 
        class="action-btn collect-btn" 
        :class="{ active: isCollected }"
        @click="handleCollect"
      >
        <van-icon :name="isCollected ? 'star' : 'star-o'" size="20" />
        <span>收藏</span>
      </div>
      <div 
        class="action-btn like-btn"
        :class="{ active: isLiked }"
        @click="handleLike"
      >
        <van-icon :name="isLiked ? 'good-job' : 'good-job-o'" size="20" />
        <span>点赞({{ likesCount }})</span>
      </div>
    </div>
  </div>
</template>

<style scoped>
.article-detail-page {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 60px;
}

/* 文章内容区域 */
.article-content-wrapper {
  padding: 16px;
  background-color: #fff;
}

/* 文章标题和阅读量 */
.article-header {
  margin-bottom: 16px;
}

.article-title {
  font-size: 22px;
  font-weight: bold;
  color: #323233;
  line-height: 1.4;
  margin-bottom: 12px;
}

.view-count {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: #969799;
}

/* 作者信息 */
.author-info {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-top: 1px solid #ebedf0;
  border-bottom: 1px solid #ebedf0;
  margin-bottom: 16px;
}

.author-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  margin-right: 12px;
  flex-shrink: 0;
}

.author-details {
  flex: 1;
}

.author-name {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
  margin-bottom: 4px;
}

.author-title {
  font-size: 13px;
  color: #969799;
  margin-bottom: 4px;
}

.author-hospital {
  font-size: 12px;
  color: #969799;
}

.follow-btn {
  flex-shrink: 0;
  height: 32px;
  padding: 0 16px;
  font-size: 14px;
}

/* 文章正文 */
.article-body {
  margin-bottom: 20px;
}

.article-intro {
  font-size: 16px;
  line-height: 1.8;
  color: #323233;
  margin-bottom: 20px;
}

.article-content {
  font-size: 16px;
  line-height: 1.8;
  color: #323233;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.article-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #323233;
  margin-bottom: 12px;
}

.section-content {
  font-size: 16px;
  line-height: 1.8;
  color: #323233;
}

.loading-text {
  text-align: center;
  color: #969799;
  padding: 40px 0;
}

/* 标签和发布时间 */
.article-footer {
  padding-top: 16px;
  border-top: 1px solid #ebedf0;
}

.article-tag {
  font-size: 13px;
  color: #1989fa;
  margin-bottom: 8px;
  display: inline-block;
}

.publish-time {
  font-size: 12px;
  color: #969799;
}

/* 底部交互栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 1px solid #ebedf0;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 16px;
  z-index: 100;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.04);
}

.comment-input {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  background-color: #f7f8fa;
  border-radius: 20px;
  font-size: 14px;
  color: #969799;
  cursor: pointer;
  min-height: 40px;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 8px;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 50px;
}

.action-btn span {
  font-size: 12px;
  color: #969799;
  white-space: nowrap;
}

.action-btn.active {
  color: #1989fa;
}

.action-btn.active span {
  color: #1989fa;
}

.collect-btn.active {
  color: #ff9500;
}

.collect-btn.active span {
  color: #ff9500;
}

.like-btn.active {
  color: #ff6b6b;
}

.like-btn.active span {
  color: #ff6b6b;
}

/* 导航栏样式 */
:deep(.van-nav-bar) {
  background-color: #fff;
}

:deep(.van-nav-bar__title) {
  font-size: 18px;
  font-weight: bold;
  color: #323233;
}

:deep(.van-nav-bar__right) {
  display: flex;
  align-items: center;
}
</style>

